package com.pro.common.log.warn.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.pro.baoyi.api.logWarn.model.db.LogFileSizeWarningConfig;
import com.pro.baoyi.api.logWarn.model.db.LogFileSizeWarningConfigMultiple;
import com.pro.common.log.warn.dao.LogFileSizeWarningConfigDao;
import com.pro.framework.api.database.IContext;
import com.pro.framework.mybatisplus.BaseService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Slf4j
@AllArgsConstructor
public class LogFileSizeWarningConfigService extends BaseService<LogFileSizeWarningConfigDao, LogFileSizeWarningConfig> {
    @Autowired
    private LogFileSizeWarningConfigMultipleService logFileSizeWarningConfigMultipleService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveOrUpdate(IContext context, LogFileSizeWarningConfig entity) {
        boolean flag = super.saveOrUpdate(entity);
        if (flag) {
            flag = this.afterSaveOrUpdate(entity);
        }
        return flag;
    }

    public boolean afterSaveOrUpdate(LogFileSizeWarningConfig entity) {
        boolean flag = logFileSizeWarningConfigMultipleService.remove(
                new LambdaQueryWrapper<LogFileSizeWarningConfigMultiple>()
                        .eq(LogFileSizeWarningConfigMultiple::getConfigId, entity.getId())
        );
        if (flag) {
            entity.getLogFileSizeWarningConfigMultiples().forEach(multiple -> {
                multiple.setConfigId(entity.getId());
                multiple.setId(null);
            });
            flag = logFileSizeWarningConfigMultipleService.saveOrUpdateBatch(entity.getLogFileSizeWarningConfigMultiples());
        }
        return flag;
    }
}
